package mya.mes.mdc.model.tag;

import mya.mes.mdc.model.excel.ExcelTagAlarmDef;
import mya.mes.mdc.model.tag.convert.ViewTagBuilder;
import mya.mes.mdc.model.tag.util.TagHolder;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class ViewTagHolder {

    private final static ViewTagHolder _instance = new ViewTagHolder();

    private final HashMap<String, ViewTag> map = new HashMap<String, ViewTag>(4096);


    public static ViewTagHolder getInstance() {
        return _instance;
    }

    public synchronized void build(TagHolder tagHolder) {
        List<MdcTag> mdcTagList = tagHolder.asList();
        HashMap<String, List<MdcTag>> tmpMap = new HashMap<String, List<MdcTag>>(4096);
        mdcTagList.forEach(mdcTag -> {
            if (mdcTag == null) {
                return;
            }
            boolean msgNotice = false;
            if (mdcTag.alarmTag != null && mdcTag.alarmTag.getExcelTagAlarmRowList() != null) {
                for (ExcelTagAlarmDef excelDef : mdcTag.alarmTag.getExcelTagAlarmRowList()) {
                    if (excelDef.getMsgNotice() != null && excelDef.getMsgNotice()) {
                        msgNotice = true;
                        mdcTag.alarmTag.msgNotice = true;
                        break;
                    }
                }
            }

            String msgNoticeTxt = "";
            if (msgNotice) {
                msgNoticeTxt = " msgNotice:true";
            }
            System.out.println(mdcTag.tagName + ":" + mdcTag.buildKey() + msgNoticeTxt);//+" isAlarm:" + (mdcTag.alarmTag != null));
            String key = mdcTag.buildKey();
            List<MdcTag> list = tmpMap.get(key);
            if (list == null) {
                list = new ArrayList<>();
                tmpMap.put(key, list);
            }
            list.add(mdcTag);
        });
        map.clear();
        ViewTagBuilder builder = new ViewTagBuilder();
        tmpMap.forEach((key, list) -> {
            ViewTag viewTag = builder.build(key, list);
            map.put(key, viewTag);
        });
    }


    public ViewTag getViewTag(String viewTagName) {
        if (viewTagName == null) {
            return null;
        }
        return map.get(viewTagName);
    }
}
